package com.tencent.wxcloudrun.util;

import cn.hutool.core.io.resource.ResourceUtil;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class PdfUtil {

    public static byte[] html2Pdf(String htmlContent) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter pdfWriter = new PdfWriter(outputStream);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        FontProvider fontProvider = new FontProvider();
        String ttc = ResourceUtil.getResource("msyh.ttc").toString();
        fontProvider.addFont(ttc + ",0", PdfEncodings.IDENTITY_H);
        ConverterProperties converterProperties = new ConverterProperties();
        converterProperties.setFontProvider(fontProvider);
        ByteArrayInputStream htmlStream = new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8));
        HtmlConverter.convertToPdf(htmlStream, pdfDocument, converterProperties);
        pdfDocument.close();
        return outputStream.toByteArray();
    }

    // 生成带尺寸控制的<img>标签
    public static String createImageTag(byte[] imageData, String width, String height) {
        String base64 = Base64.getEncoder().encodeToString(imageData);
        return String.format("<img src='data:image/png;base64,%s' style='width:%s; height:%s;'>", base64, width, height);
    }
}
